<template>
  <div class="wrapper">
    <Spin :spinning="loading" tip="Loading...">
      <div>
        <BreakSpace label="拒赔申诉信息" :containerStyle="{ marginBottom: '10px' }" />
        <FormPanel ref="infoMain" :list="formList" :cols="3" @formChange="changeHandle" :labelWidth="85" :isSubmitBtn="false" />
        <Spin :spinning="loading" tip="Loading...">
          <FilterTable ref="fileTable" :columns="columnsFile" columnsRef="whbydUploadFile" :isSelectColumn="false" :is-toper-info="false"
                       :onColumnsChange="columnsFile => (this.columnsFile = columnsFile)" height="auto" :dataSource="list" />
        </Spin>
      </div>
      <div>
        <Drawer :visible.sync="visibleEdit" :title="'索赔单明细'" destroyOnClose width="100%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
          <editForm @close="editclose" @save="editsave" :rowData="row" :isDetailed="false"></editForm>
        </Drawer>
        <BreakSpace label="回运清单" :containerStyle="{ marginBottom: '10px' }" />
        <template>
          <FilterTable ref="table1" :columns="columns" :dataSource="dataList" :datakey="'items'" :onColumnsChange="columns => (this.columns = columns)" :onRowSelectChange="selectChange"
                       selectionType="single" height="auto" :isPagination="false" :isSelectColumn="false">
          </FilterTable>
        </template>
      </div>
      <!--      <div v-show="!isDorJ">-->
      <!--        <div v-show="!isDetailed">-->
      <div>
        <div v-show="!isDorJ">
          <BreakSpace label="申诉后清单" :containerStyle="{ marginBottom: '10px' }" />
          <template>
            <FilterTable ref="table2" :columns="columns2" :dataSource="dataList1" :datakey="'items'" :onColumnsChange="columns2 => (this.columns2 = columns2)" :onRowSelectChange="selectChange"
                         selectionType="single" height="auto" :isPagination="false" :isSelectColumn="false">
            </FilterTable>
          </template>
        </div>
      </div>
      <div>
        <BreakSpace label="审核信息" :containerStyle="{ marginBottom: '10px' }" />
        <FormPanel :cols="3" :list="form2" :formType="type" :isSubmitBtn="false" ref="examineinfoChanges" />
      </div>
      <div>
        <BreakSpace label="审核记录" :containerStyle="{ marginBottom: '10px' }" />
        <FilterTable
          ref="table3"
          :columns="columnsLog"
          :fetchapi="fetchApi"
          :params="fetchParams"
          :isSelectColumn="false"
          :datakey="'records'"
          columnsRef="notification_maintain_index_01"
          :onColumnsChange="columns => (this.columns = columns)"
        >
        </FilterTable>
      </div>
    </Spin>
    <div class="dialogBottmView">
      <el-button @click="closeDialog()">关 闭</el-button>
      <el-button @click="saveDialog(true)" v-if="!isDetailed" type="primary">审核通过</el-button>
      <el-button @click="saveDialog(false)" v-if="!isDetailed" type="primary">审核驳回</el-button>
    </div>
  </div>
</template>

<script>
import config from '@/assets/js/config';
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import moment from "moment";
import Cookies from 'js-cookie';
import { getListByExampleWhere, getByPermissionCtrl } from '@/api/dictionary/index.js';
import { addRefusalToClaim, getClaimForm, examineRefusalToClaim ,getRefusalToClaimLog,getRefusalToClaimPart} from '@/api/claim/factory/refusalToClaim';
import { findFileByUrl } from '@/api/partsmanage/financialManagement/capitalAccount/index'
import editForm from '../../claimDemage/BasicData/ClaimQueryFactory/editForm';
export default {
  name: "AddForm",
  mixins: [authority, dictionary],
  props: {
    type: {
      type: String,
      required: true
    },
    row: {
      type: Object,
      required: true
    }
  },
  components: {
    editForm
  },
  data() {
    return {
      formList: this.createFormList(),
      fetchApi: getRefusalToClaimLog,//api 接口 table请求数据入口
      isDetailed: true,
      columns: this.creatHeader(),
      columnsLog:this.exlog(),
      columns2: this.creatHeader2(),
      columnsFile: this.createdTable(),
      form1: {
        fileList: []
      },
      visibleEdit: false,
      form2: this.createForm2(),
      dataList: [],
      dataList1: [],
      uploadPrefix: config.uploadUrl,// 附件上传前缀
      cmsClaimType: 55681001,
      loading: false,
      whCode: null,
      list: [],
      delFile: [],
      isDorJ:true,
      resData: {},
      userDealerCode: Cookies.get('serviceDealerCode'),
      selectedRows: [], //选中经销商
      fetchParams: {id:this.row.id}
    };
  },
  async created() {
    this.loading = true;
    this.isDetailed = this.type == 'detailed'?true:false;
    this.isDorJ = this.row.complainType == 55681001 ?true:false;
    this.edit();
    this.loading = false;
  },
  // 页面加载完成 请求接口
  mounted() {
    // this.list = this.row.file;
  },
  methods: {

    createFormList() {
      let isShow = this.row.complainType == 55681001?true:false;
      return [
        { type: 'INPUT', label: '拒赔申诉单号', fieldName: 'claimRefusalNo', placeholder: '请选择', initialValue: '', disabled: true },
        { type: 'INPUT', label: '服务中心代码', fieldName: 'dealerCode', placeholder: '请选择', initialValue: '', disabled: true },
        { type: 'INPUT', label: '服务中心名称', fieldName: 'dealerName', placeholder: '请选择', initialValue: '', disabled: true },
        { type: 'INPUT', label: '拒赔申诉类型', fieldName: 'complainType', placeholder: '请选择', initialValue: '', disabled: true },
        { type: 'INPUT',
          label: '索赔单号',
          fieldName: 'cmsClaimNo',
          placeholder: '请选择',
          initialValue: '',
          readonly:true,
          unitRender: p => {
            return (
              <div>
                <multiuse-button icon="el-icon-document" onClick={() => this.claimDetail()}/>
              </div>
            );
          }, },
        { type: 'INPUT', label: '索赔单状态', fieldName: 'claimStatus', placeholder: '请选择', initialValue: '', disabled: true },
        { type: 'INPUT', label: 'VIN', fieldName: 'vin', placeholder: '请选择', initialValue: '', disabled: true },
        { type: 'INPUT', label: '车型名称', fieldName: 'modelName', placeholder: '请选择', initialValue: '', disabled: true },
        { type: 'INPUT', label: '索赔类型', fieldName: 'cmsClaimType', placeholder: '请选择', initialValue: '', disabled: true },
        { type: 'INPUT', label: '旧件仓库', fieldName: 'whCode', placeholder: '',hidden: isShow, disabled: true },
        { type: 'INPUT', label: '申诉人', fieldName: 'complainBy', placeholder: '请选择', initialValue: '', disabled: true },
        { type: 'INPUT', label: '申诉电话', fieldName: 'complainMobile', placeholder: '请选择', initialValue: '', disabled: true },
        {
          type: 'TEXT_AREA',
          label: '申诉理由',
          fieldName: 'complainReason',
          placeholder: '请选择',
          initialValue: '',
          disabled: true,
          selfCols: 2,
          rows: 5
        }
      ];
    },
    creatHeader() {
      let isDetailed = this.type == 'detailed' ? true : false;
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            console.log('2121212121', props)
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '操作',
        //   dataIndex: 'column-action',
        //   width: 90,
        //   hidden: isDetailed,
        //   render: (props) => {
        //     return (
        //       <div>
        //         <el-button size="mini" type="text" onClick={() => this.delVideo2(props.row, true)}>
        //           删除
        //         </el-button>
        //       </div>
        //     );
        //   }
        // },
        { title: '索赔id', dataIndex: 'cmsClaimId', sorter: true, hidden: true },
        { title: '是否主因件', dataIndex: 'isMain', sorter: true },
        { title: '回运单号', dataIndex: 'returnNo', sorter: true },
        {title: '回运类型', dataIndex: 'returnType', sorter: true,
          render: props => {
            return <div>{this.createDictText(props.row.returnType, '5595')}</div>;
          }},
        { title: '旧件id', dataIndex: 'partId', sorter: true, hidden: true },
        { title: '旧件代码', dataIndex: 'partCode', sorter: true },
        { title: '旧件名称', dataIndex: 'partName', sorter: true },
        { title: '采购渠道代码', dataIndex: 'supCode', sorter: true },
        {
          title: '旧件数量',
          dataIndex: 'partCount',
          sorter: true
        },
        {
          title: '实际回运数量',
          dataIndex: 'actualPartCount',
          sorter: true
        },
        // {title: '入库数量', dataIndex: 'inCount',sorter: true},
        { title: '不合格数量', dataIndex: 'unqualifiedCount', sorter: true }
      ]
    },
    exlog(){
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        { title: '操作人', dataIndex: 'checkBy', sorter: true,},
        { title: '操作状态', dataIndex: 'status', sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.status, '5503')}</span>;
          }},
        { title: '操作时间', dataIndex: 'checkAt', sorter: true,dateFormat: 'yyyy-MM-dd HH:mm'},
        { title: '操作说明', dataIndex: 'opinion', sorter: true}
      ];
    },
    creatHeader2() {
      let isDel = this.type == "detailed"?true:false;
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            console.log('2121212121', props)
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 90,
          hidden: this.isShow,
          render: (props) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.delVideo2(props.row, false)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        { title: '索赔id', dataIndex: 'cmsClaimId', sorter: true, hidden: true },
        { title: '是否主因件', dataIndex: 'isMain', sorter: true },
        { title: '回运单号', dataIndex: 'returnNo', sorter: true },
        {title: '回运类型', dataIndex: 'returnType', sorter: true,
          render: props => {
            return <div>{this.createDictText(props.row.returnType, '5595')}</div>;
          }},
        { title: '旧件id', dataIndex: 'partId', sorter: true, hidden: true },
        { title: '旧件代码', dataIndex: 'partCode', sorter: true },
        { title: '旧件名称', dataIndex: 'partName', sorter: true },
        { title: '采购渠道代码', dataIndex: 'supCode', sorter: true },
        {
          title: '旧件数量',
          dataIndex: 'partCount',
          sorter: true,
          width: 100
        },
        {
          title: '入库数量',
          dataIndex: 'inCount',
          sorter: true,
          editable: true,
          editType: 'number',
          width: 200,
          render: p => {
            console.log("max", p.row.partCount - p.row.unqualifiedCount)
            // let maxNum = p.row.partCount - p.row.unqualifiedCount;
            return <el-input-number disabled={isDel} type="text" v-model={p.row.inCount} max={p.row.partCount} min={0} controls={false} precision="0"/>
          }
        },
        // {title: '入库数量', dataIndex: 'inCount',sorter: true},
        {
          title: '不合格数量',
          dataIndex: 'unqualifiedCount',
          sorter: true,
          editable: true,
          editType: 'number',
          max: 99999999,
          min: 0,
          width: 200,
          // onChange:((x,y)=>{
          //   console.log("yyyyyy",y)
          //   if(y.unqualifiedCount<=y.partCount){
          //
          //   }
          // })
          render: p => {
            console.log("max", p.row.partCount - p.row.inCount)
            // let maxNum = p.row.partCount - p.row.inCount;
            return <el-input-number disabled={isDel} type="text" v-model={p.row.unqualifiedCount} max={p.row.inCount} min={0} controls={false} precision="0"/>
          }
        },
        {
          title: '合格数量',
          dataIndex: 'qualifiedCount',
          sorter: true,
          render: p => {
            let qualifiedCount = p.row.inCount - p.row.unqualifiedCount;
            if (qualifiedCount >= 0) {
              p.row.qualifiedCount = qualifiedCount;
              return <span>{qualifiedCount}</span>
            } else {
              p.row.qualifiedCount = 0;
              return <span>{0}</span>
            }
          }
        }
      ]
    },
    createForm2() {
      let isDetailed = this.type == 'detailed' ? true : false;
      return [
        {
          type: 'TEXT_AREA',
          label: '审核意见',
          fieldName: 'opinion',
          placeholder: '请输入',
          initialValue: '',
          selfCols: 3,
          rows: 7,
          maxlength: 300,
          disabled: isDetailed
        }
      ]
    },
    createdTable() {
      let isDetailed = this.type == 'detailed' ? true : false;
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '附件标题(支持 jpg,png,pdf格式,文件大小不超过 5M)',
          dataIndex: 'title',
          showOverflowTooltip: true,
          render: p => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.downloadFile(p.row.fileUrl)}>
                  {p.row.title}
                </el-button>
              </div>
            );
          }
        },
        {
          title: '上传日期',
          dataIndex: 'createdAt',
          dateFormat: 'yyyy-MM-dd HH:mm'
        }
      ];
    },
    async edit() {
      console.log("res======", this.row);
      this.formList.forEach(x => {
        if ('cmsClaimType' == x.fieldName) {
          console.log('cmsClaimType',this.row.cmsClaimType)
          x.initialValue = this.createDictText(this.row.cmsClaimType,'5510'); //vin
        } else if ('claimStatus' == x.fieldName) {
          x.initialValue = this.createDictText(this.row.claimStatus,'5513'); //vin
        }else if('complainType' == x.fieldName){
          x.initialValue = this.createDictText(this.row.complainType,'5568'); //vin
        } else{
          x.initialValue = this.row[x.fieldName];
        }
      });
      this.form2.forEach(x =>{
        x.initialValue = this.row[x.fieldName];
      });
      const res = await getRefusalToClaimPart({
        id:this.row.id
      });
      if(this.type != 'edit'){
        this.columns2.find(x => x.dataIndex == 'column-action').hidden =true;
        this.saveMaintainItemSelect(res.data.newData ,"newData");
      }
      this.saveMaintainItemSelect(res.data.oldData ,"oldData");
      let fileList = JSON.parse(JSON.stringify(this.row.file));
      this.$refs.fileTable.EXECUTE_INSERT(fileList);
    },
    successHandler(val) {
      if (this.list.length >= 5) {
        this.$notify.error({ title: '提示信息', message: '文件上传不能超过5个!' });
      } else {
        this.loading = false;
        if (val && val.length > 0) {
          if (val[0].url.errorList && val[0].url.errorList.length > 0) {
            this.errorList = val[0].url.errorList;
          } else {
            let json = JSON.parse(JSON.stringify(val));
            let data = {};
            data.createdAt = moment().format('YYYY-MM-DD HH:mm:ss');
            data.title = json[json.length - 1].name;
            data.fileUrl = json[json.length - 1].url;
            this.$refs.fileTable.$refs.pageTable.EXECUTE_INSERT(data);
          }
        } else {
          this.errorList = [];
        }
      }
    },
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    closeDialog() {
      this.$emit('close');
    },
    async saveDialog(isEscalation) {
      if (isEscalation == false && this.form2.find(x => x.fieldName === 'opinion').initialValue === null) {
        this.$notify.error({ title: '提示信息', message: '驳回时要写审核意见!' });
      } else {
        let [err1, data1] = await this.$refs.examineinfoChanges.GET_FORM_DATA();
        console.log('this.resData1111', this.rowData)
        console.log('this.dataList', this.dataList1)
        let returnTypes = this.dataList1.filter(item => item.returnType === 55951002);
        let xss = false;
        returnTypes.forEach(x=>{
          this.dataList1.forEach(y=>{
            if(y.returnType == 55951001 && y.partCode == x.partCode){
              let count = y.inCount+x.inCount;
              if(count>y.partCount){
                xss = true;
                this.$notify.error({ title: '提示信息', message: `旧件名称为 "${y.partName}" 的常规回运和紧急回运的入库数量和不能超过旧件数量!`});
                return;
              }
            }
          })
        })
        if(xss) return;
        let data = Object.assign({},
          this.row,
          ...this.rowData,
          data1,
          {newdata:this.dataList1,olddata:this.dataList,escalation:isEscalation}
        );
        console.log('data', data);
        let res = await examineRefusalToClaim(data);
        if (res.resultCode == 200) {
          this.$notify.success({ title: '提示信息', message: '操作成功!' });
          this.$emit('close', { type: 'refresh' });
        }
      }
    },
    claimDetail() {
      console.log('122222224====',this.rowData)
      this.visibleEdit = true;
    },
    editclose() {
      this.visibleEdit = false;
    },
    editsave() {
      this.visibleEdit = false;
      this.fetchParams = { ...this.fetchParams };
    },
    saveMaintainItemSelect(val,type) {
      console.log("type",type)
      console.log("val",val)
      // if(this.type == 'add'){
      //   this.rowData = val;
      //   console.log('111111111',val)
      //   this.visibleMaintainItemSelect = false;
      //   this.dataList = val[0].returnDtl;
      //   this.dtlID = [];
      //   val[0].returnDtl.forEach(v=>this.dtlID.push(v.dtlIds))
      //   console.log("this.dtlID ",this.dtlID )
      //   this.formList.map(x => {
      //     if ('vin' == x.fieldName) {
      //       x.initialValue = val[0].vin; //vin
      //     }
      //     if ('modelName' == x.fieldName) {
      //       x.initialValue = val[0].modelName; //vin
      //     }
      //     if ('cmsClaimType' == x.fieldName) {
      //       console.log('cmsClaimType',val[0].cmsClaimType)
      //       x.initialValue = this.createDlrDictText(val[0].cmsClaimType,'5510'); //vin
      //     }
      //     if ('cmsClaimNo' == x.fieldName && this.type == 'add') {
      //       x.initialValue = val[0].cmsClaimNo; //vin
      //     }
      //     if ('claimStatus' == x.fieldName) {
      //       x.initialValue = this.createDlrDictText(val[0].claimStatus,'5513'); //vin
      //     }
      //   });
      // }else{
      if(type == 'oldData') {
        this.rowData = val;
        console.log('111111111', val)
        this.dataList = val;
        this.dtlID = [];
        val.forEach(v => this.dtlID.push(v.dtlIds))
        console.log("this.dtlID ", this.dtlID)
        if(this.type == 'edit'){
          this.$refs.table2.$refs.pageTable.EXECUTE_INSERT(val);
        }
      }else{
        this.dataList1 = val;
        this.$refs.table2.$refs.pageTable.EXECUTE_INSERT(val);
      }
      //}
    },
    async changeSeriesSelect(val) {
      console.log('传参', val);
      const res = await getListByExampleWhere({ whCode: val });
      console.log('res', res);
      res.data.find(x => {
        if (x.whCode === val) {
          this.whId = x.whId;
          this.whName = x.whName;
          this.formList.find(x => x.fieldName == 'expressAddress').initialValue = x.whAddress;
          this.formList.find(x => x.fieldName == 'conPerson').initialValue = x.cPerson;
          this.formList.find(x => x.fieldName == 'conTel').initialValue = x.cTel;
          this.formList.find(x => x.fieldName == 'email').initialValue = x.eMail;
          console.log(res.data);
        }
      });
      // this.$refs.table1.$refs.pageTable.EXECUTE_DELETE(this.$refs.table1.$refs.pageTable.list);
      console.log(this.whId);
    },
    async changeComplainType(val) {
      console.log('传参', val);
      this.formList.forEach(x => {
        if (x.fieldName != 'complainType') {
          x.initialValue = '';
        }
      });
      this.dataList = [];
      this.cmsClaimType = val;
    },
    // 执行下载动作
    async downloadFile(url) {
      console.log(url)
      const data = await this.downLoadByUrl(url);
      console.log('downloadUrl=====', data)
      let a = document.createElement('a');
      a.href = data;
      a.target = '_blank';
      a.click();
      a = null;
    },
    async downLoadByUrl(url, params = {}) {
      url = encodeURIComponent(url);
      let res = await findFileByUrl(url);
      console.log(res.data)
      return res.data;
    },
    delVideo(val) {
      console.log('#@!#!', val);
      this.$refs.fileTable.$refs.pageTable.EXECUTE_DELETE([val]);
      this.delFile.push(val.fileId);
      console.log(this.delFile);
    },
    delVideo2(val, type) {
      console.log('#@!#!', val);
      console.log('dataList1', this.dataList1);
      if(this.dataList1.length<=1){
        this.$notify.error({ title: '提示信息', message: '至少要有一个申诉后清单！' });
      }else {
        type ? this.$refs.table1.$refs.pageTable.EXECUTE_DELETE([val]) : this.$refs.table2.$refs.pageTable.EXECUTE_DELETE([val]);
        this.dtlID = this.dtlID.filter(i => i != val.dtlIds);
        console.log('this.dtlID', this.dtlID);
      }
    },
    changeHandle(data) {
    }
  }
}
</script>

<style scoped>

</style>
